﻿using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using Newtonsoft.Json;
using Growatt.ShinebusService.Helper;

namespace Growatt.UploadPackService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IJwtTokenService _tokenService;
        private readonly IUserRepository _userRepository;

        public AuthController(IJwtTokenService tokenService, IUserRepository userRepository)
        {
            _tokenService = tokenService;
            _userRepository = userRepository;
        }

        [HttpPost("login")]
        public IActionResult Login([FromBody] LoginModel model)
        {
            // 验证用户凭据（例如数据库验证）
            if (!ValidateUser(model.Username, model.Password))
            {
                return Unauthorized("用户名或密码不正确");
            }

            // 生成令牌
            var token = _tokenService.GenerateToken(model.Username, new[] { "Admin" });

            return Ok(new { Token = token });
        }

        private bool ValidateUser(string username, string password)
        {
            // 获取存储的用户信息
            var user = _userRepository.GetUserByUsername(username);
            if (user == null)
            {
                return false;
            }

            // 使用存储的盐值对用户输入的密码进行哈希处理，并与存储的哈希密码进行比较
            return HashPasswordWithSalt(password, user.Salt) == user.HashedPassword;
        }

        private string HashPasswordWithSalt(string password, string salt)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                // 将密码和盐值组合
                byte[] passwordWithSalt = Encoding.UTF8.GetBytes(password + salt);
                byte[] hashBytes = sha256.ComputeHash(passwordWithSalt);
                return Convert.ToBase64String(hashBytes);
            }
        }
    }
    public class LoginModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    public class User
    {
        public string Username { get; set; }
        public string HashedPassword { get; set; }
        public string Salt { get; set; }
    }
    public interface IUserRepository
    {
        User GetUserByUsername(string username);
    }
    public class UserRepository : IUserRepository
    {
        private readonly string _usersFilePath;

        public UserRepository()
        {
            // 获取可执行文件所在的目录
            string exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            // 构建users.json文件的完整路径
            _usersFilePath = Path.Combine(exeDirectory, "Config", "users.json");
        }

        public User GetUserByUsername(string username)
        {
            // 从JSON文件中读取用户信息
            var users = LoadUsersFromJsonFile();
            return users.FirstOrDefault(u => u.Username == username);
        }

        private List<User> LoadUsersFromJsonFile()
        {
            if (!File.Exists(_usersFilePath))
            {
                File.Create(_usersFilePath).Close();

                var str = DuiHelperJson.ObjectToJson(new List<User>() { new User { Username = "OA_Admin", HashedPassword = HashPasswordWithSalt("OA_Admin_Password", "salt"), Salt = "salt" } });
                File.WriteAllText(_usersFilePath, str);
            }
            var jsonContent = File.ReadAllText(_usersFilePath);
            return JsonConvert.DeserializeObject<List<User>>(jsonContent);
        }

        private string HashPasswordWithSalt(string password, string salt)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                // 将密码和盐值组合
                byte[] passwordWithSalt = Encoding.UTF8.GetBytes(password + salt);
                byte[] hashBytes = sha256.ComputeHash(passwordWithSalt);
                return Convert.ToBase64String(hashBytes);
            }
        }
    }
}
